<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Google
 *
 * @author dragon.hu add @2016.4.8
 */
require_once 'BaseChannel.php';

//韩国SDK
class Koreasdk implements BaseChannel 
{
	//static $googlekey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzhGHXr6hY8l77HbdM37CLN/6K6sOhgu+TRc1evqjduxMK1VGYAFIadmqlkS1j1zDBLCNz8ot3TRg98i1bpFywKL1vP8LGvDCAi/eXODiqlO3bhqwvzd5aAoCu+W1srxalsOMYsCtOCGh/NP1ET2wP+4jjF9BCOGygEPlSDpXmqJUbMPRE9wrzxFXmA1W/BPlLx8OzdrCHjE3JEMpq5uD+ZIeC3+RIHx7y/4UGXmlUKjjo7uKF2bBdWiubKxRgTXaw0uETYJtv/7K8Fq4vny2f+pucnd8IOqxt2tbQ3zRvYOKXknQgTWbRqc3Sy5FW21oxhoCKc2UJMKSINgKZaXZYQIDAQAB";
	static $googlekey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj0FybRM6iH2mYYevTGKG5/SCVrBQox1s1QL5PUyeNVOCqtitriG3+D46YW08VqMKsrmdfw2BpQQhgHQB5kEPRBoTORkTUOKTx9eGV/xinR/aIGriOhqa8CNzyOJNfyl+xzZO/UWvaKlMFUutaxV9ezMpyia5+NDkV2Dgs26lIk8J6dj84rgBgfHszHf09Pjz9erX/7oUFMBVYce3ZWVU42juHkCRpKBHt9Km8KocrbR5LeUtiQWFIANgZUuzAeUMJRl4F38UpgaBvYFEsP8gRHMXS5/st/LrcGvRbuXjya4fhc8TjBDXNwbshgjy8uIjEqkVPzs5papsltJsYmpbIQIDAQAB";
	function __construct() 
	{
		//echo "construct";
	}

	function android($data)
	{
		//echo $ret;
	}
	
	function ios($data)
	{
		//echo $ret;
	}
	
	function payverify()
	{
		$publickey = "";  //谷歌支付的publickey
		$orderLog = new ChargeOrder();
		//var_dump($_REQUEST);
		//exit();
		$orderLog->log("googlekorea", $_REQUEST);
		//1.接收客户端传来的数据
		
		//$request = file_get_contents("php://input");
		$purchaseData = stripslashes($_REQUEST['purchaseData']);
		$dataSignature = stripslashes($_REQUEST['dataSignature']);
		$roleid = $_REQUEST['roleid'];
		$serverid = $_REQUEST['serverid'];
		$orderid = $_REQUEST['orderid'];
		$money = $_REQUEST['money'];
		//2.sign验证
		//var_dump(self::$googlekey);
		//var_dump($purchaseData);
		//var_dump($dataSignature);
		//var_dump($purchaseData);
		//var_dump($dataSignature);
		$return = $this->chkGooglePlay(self::$googlekey, $purchaseData, $dataSignature);
		//var_dump($return);
		//exit();
		if ($return)
		{
			//进行发货
			if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $orderid, "googlekorea", ANDROID))
			{
				$ret="failure";
				$orderLog->log("googlekorea",array("order"=>$orderid,"money"=>$money,"serverresult"=>"faild"));
			}
			else
			{
				//支付成功
				$ret="success";
				$orderLog->log("googlekorea",array("order"=>$orderid,"money"=>$money,"serverresult"=>"success"));
			}
		}
		else
		{
			$ret="failure";
			$orderLog->log("googlekorea",array("order"=>$orderid,"money"=>$money,"serverresult"=>"signfaild"));
		}
		return $ret;
	}
	
	/*
	 *  谷歌V3商城校验,网上找到的验证代码，感谢原作者O(∩_∩)O~
	 */
	function chkGooglePlay($public_key, $purchaseData, $signature) 
	{
		/*
		 $public_key=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn8Zo/abcdbRKBJl0VJLTk/O9Vca9mPiI4iEE+kiBrC7+zaZLuCaNN2v/38327TerDOAbp6BKXHl4p6J8Hf1kcja62W9lA+21/Qetrg1O6Q2pVNvWQnnlMzYHjFGChBclaMg20faVFPUFXfbRMEIsNbig5qu2Vg3fRQisQAmBIpKktnV5zOOw7gXfx3+EFql/87dhtk8gsnzvtYKu9iec98asctZ8FbpkNpyrh3czjXm/HnIUILPjLCRHX5Uk1zv7X7k0DbGbYFttdAQbi1byrZ2W5sbF93Cpy9NmldivnOFWLiqhiyck2Zsy3TDKMFnlrnI0gL1/AbCd67V7/d04NwIDAQAB
		 */
		$key =    "-----BEGIN PUBLIC KEY-----\n".
				chunk_split($public_key, 64,"\n").
				'-----END PUBLIC KEY-----';
		$key = openssl_get_publickey($key);
		$signature = base64_decode($signature);
		$ok = openssl_verify($purchaseData, $signature, $key, OPENSSL_ALGO_SHA1);//openssl_verify() 函数来验证sign签名是否正确，是通过指定的data数据和公钥相关的pub_key_id来实现的
		if($ok=='1') {
			return true;
		} else {
			return false;
		}
	}
	
	/****************************onestore的支付验证流程dragon.hu add @2016.4.9*********************************/
	function ospayverify()
	{
		$orderLog = new ChargeOrder();
		$orderLog->log("onestore", $_REQUEST);
		//1.客户端发过来的数据
		$data['txid'] = $_REQUEST['txid'];
		$data['appid'] = $_REQUEST['appid'];
		$data['signdata'] = $_REQUEST['signdata'];
		$money = $_REQUEST['money'];
		$orderid = $_REQUEST['orderid'];
		$sendarr = json_encode($data);

		//$recievedata = iosvpost("https://iap.tstore.co.kr/digitalsignconfirm.iap", 30, $sendarr);  //正式地址
		$recievedata = iosvpost("https://iapdev.tstore.co.kr/digitalsignconfirm.iap", 30, $sendarr);  //测试地址
		$orderLog->log("onestore", $recievedata);  //记录下返回
		$recievearr = json_decode($recievedata, true);
		
		//是否要进行appid和productid和chargeamount等的验证？
		
		$detail = $recievearr['detail'];
		$message = $recievearr['message'];
		//var_dump($recievearr);
		//exit();
		if ($recievearr['status'] == 0)
		{
			//进行发货
			if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $orderid, "onestore", ANDROID))
			{
				$ret="failure";
				$orderLog->log("onestore",array("order"=>$orderid,"money"=>$money,"serverresult"=>"faild"));
			}
			else
			{
				//支付成功
				$ret="success";
				$orderLog->log("onestore",array("order"=>$orderid,"money"=>$money,"serverresult"=>"success"));
			}
		}
		else
		{
			$ret = "failure";
			$orderLog->log("onestore", "faliure orderid:$orderid,detail:$detail,message:$message");
		}
		return $ret;
	}
	/***********************************礼包推送的接口dragon.hu add @2016.4.13***********************************/
	function getPushGift()
	{
		include CONFIGPATH.'db.php';
		$receivearr = $_REQUEST;
		//m_GMToolPath + "payment/Koreasdk/getPushGift?area_id=" + IntToStr(area_id) + "&role_id=" + IntToStr(role_id) + "&giftbag_id=" + IntToStr(giftbag_id);
		$serverid = $_REQUEST['area_id'];
		$roleid = $_REQUEST['role_id'];
		$giftbagid = $_REQUEST['giftbag_id'];
		
		$str = "serverid=".$serverid."&roleid=".$roleid."&giftbagid=".$giftbagid;
		log_message("getPushGift:".$str, "Korea");
		//0 发送邮件成功 1 已结领取 2 发送邮件失败result areaid roleid giftbag_id
		$response = array();
		//此角色是否已领取了这个礼包
		$gmconn = new Database($config['db']);
		$sql = "SELECT * FROM korea_giftstatus WHERE serverid = $serverid AND roleid = $roleid AND giftbagid = $giftbagid";
		$one = $gmconn->one($sql);
		if (isset($one))
		{
			$response['result'] = 1;  //1表示已领取
			$response['areaid'] = (int)$serverid;
			$response['roleid'] = (int)$roleid;
			$response['giftbag_id'] = (int)$giftbagid;
			log_message("getPushGift:".$str." already used", "Korea");
			echo json_encode($response);
			return;
		}
		$tmpret = self::sendGiftToPlayer($serverid, $roleid, $giftbagid);
		//b.记录存表
		if ($tmpret)
		{
			$nowtime = date("Y-m-d H:i:s", time());
			$sql = "INSERT INTO korea_giftstatus(serverid, roleid, giftbagid, giftbagstatus, finishtime) VALUES(".
					$serverid.", ".$roleid.", '".$giftbagid."', 1, '$nowtime')";
			if($gmconn->execute($sql))
			{
				$response['result'] = 0;  //0表示发送成功
				$response['areaid'] = (int)$serverid;
				$response['roleid'] = (int)$roleid;
				$response['giftbag_id'] = (int)$giftbagid;
				log_message("getPushGift:".$str." success!!!!", "Korea");
				echo json_encode($response);
				return;
			}
		}
		$response['result'] = 2;  //2表示发送失败
		$response['areaid'] = (int)$serverid;
		$response['roleid'] = (int)$roleid;
		$response['giftbag_id'] = (int)$giftbagid;
		echo json_encode($response);
		log_message("getPushGift:".$str." other error", "Korea");
		return;
	}
	
	/*
	 * 发放奖励的接口
	 * @param $serverid为发送的服务器id
	 * @param $roleid为发送的角色id
	 * @param $key为礼包id
	 * @return 成功true，失败false
	 */
	static function sendGiftToPlayer($serverid, $roleid, $key) {
		// 获取到奖励物品信息
		include CONFIGPATH.'db.php';
		//$dynconn = getTmpDbConnect ( PLATFORM_ALL, 'all', $serverid, DBTYPE_DYNAMIC );
		$conn = new Database($config['center_db']);
	
		$rowdata = array ();
		$i = 0;
		$sql = "SELECT * FROM dynamic_giftbagdetail WHERE giftbagid = $key";
		$conn->query ( $sql );
		while ( $n = $conn->get_array () ) {
			$rowdata ['item'] [$i] = $n ['objectid'];
			$rowdata ['amount'] [$i] = $n ['maxcount'];
			$rowdata ['equiplevel'] [$i] = 0; // 装备等级，默认置0
			$i ++;
		}
	
		$strparam = "";
		$i = 0;
		while ( (! empty ( $rowdata ["item"] [$i] )) && (! empty ( $rowdata ["amount"] [$i] )) ) {
			$strparam .= "item$i=" . $rowdata ['item'] [$i] . "&amount$i=" . $rowdata ['amount'] [$i] . "&equiplv$i=" . $rowdata ['equiplevel'] [$i] . "&";
			$i ++;
		}
	
		$sendData = array ();
		// 填充基本信息
		$sendData ['mail_title'] = "邮件标题"; // 这个要写成什么样
		$sendData ['keep_time'] = - 1; // 由游戏服来修改时间
		$sendData ['mail_content'] = "邮件内容"; // 这个要写成什么样
		$sendData ['receiver_id'] = $roleid;
	
		$allurl = get_area_list_url ();
		$host = $allurl [$serverid];
		$strUrl = $host . array_to_stringparam ( $sendData ) . $strparam . "action=15"; // !!!!!注意权限过滤
		// print_r($strUrl);
		// exit(0);
		$strResult = vpost ( $strUrl );
		if ($strResult == 1 || $strResult == 4) // 1是发送成功，4是转为离线发送
		{
			return true;
		}
		return false;
	}
	
}